export const useBaseStore = defineStore('base', () => {
  // 标签列表管理
  let roleCode = $ref([])
  let tagNavList = $ref([])
  const updateTags = (list) => {
    tagNavList = list.filter(e => e.fullPath !== '/')
  }
  const addTag = (router) => {
    if (router.fullPath === '/') return
    const tagIdx = tagNavList.findIndex(e => e.fullPath === router.fullPath)
    if (tagIdx > -1) {
      tagNavList.splice(tagIdx, 1, router)
    } else {
      tagNavList.push(router)
    }
  }
  const closeTag = (fullPath) => {
    const idx = tagNavList.findIndex(e => e.fullPath === fullPath)
    if (idx > -1) {
      tagNavList.splice(idx, 1)
    }
  }
  const closeOtherTag = (idx) => {
    const router = tagNavList[idx]
    tagNavList = []
    if (idx !== -1) {
      tagNavList.push(router)
      roleCode.forEach((e, i) => {
        if (e.menuPath !== router.path) {
          roleCode.splice(i, 1)
        }
      })
    }
  }
  const clearTags = () => {
    tagNavList = []
  }
  const closeAllTag = () => {
    tagNavList = []
    // iframeTabList.value = []
    // companys.value = []
    roleCode = []
  }

  // 加载状态管理
  let loading = $ref(false)
  const showLoading = () => {
    loading = true
  }
  const hideLoading = () => {
    loading = false
  }

  // UI界面管理
  let theme = $ref({
    collapsed: false,
    isDark: false,
  })
  const toggleCollapse = () => {
    theme.collapsed = !theme.collapsed
  }
  // 刷新缓存管理
  let refreshCache = $ref(null)
  const addRefreshCache = (path) => {
    refreshCache = path
  }
  const delRefreshCache = () => {
    refreshCache = null
  }
  // 乾坤环境判定
  let isQiankun = $ref(false)
  const setQiankun = (payload) => {
    isQiankun = payload
  }

  // 数据清空
  const clearBase = () => {
    tagNavList = []
    refreshCache = null
  }

  //  TODO: 关闭当前页面，并跳转到新页面。先跳转到 /blank 是为了清除 keep-alive 缓存。
  // const route = useRoute()
  // const router = useRouter()
  // const redirectTo = (newPath) => {
  //   closeTag(route.fullPath)
  //   addRefreshCache(route.fullPath)
  //   router.push({ path: '/blank', query: { redirect: newPath } })
  // }

  return {
    loading: $$(loading),
    tagNavList: $$(tagNavList),
    theme: $$(theme),
    isQiankun: $$(isQiankun),
    refreshCache: $$(refreshCache),
    showLoading,
    hideLoading,
    updateTags,
    addTag,
    closeTag,
    closeOtherTag,
    clearTags,
    closeAllTag,
    toggleCollapse,
    addRefreshCache,
    delRefreshCache,
    setQiankun,
    clearBase,
    // redirectTo,
  }
}, { unistorage: { key: 'config-base' } })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useBaseStore, import.meta.hot))
